﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.ApplicationServer.Http;
using ApiPrototype.Handlers;

namespace ApiPrototype
{
    public class iphlWebApiConfiguration : WebApiConfiguration
    {
        public iphlWebApiConfiguration(bool testClient = false)
            :base()
        {
            EnableTestClient = testClient;
            
            /*
             * Enable Basic Authentication
             * Not using this for now*/
            Security = (r, e) =>
            {
                e.Mode = HttpBindingSecurityMode.Transport;
                //e.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Basic;
            };
            

            // Add operation handlers
            RequestHandlers = (h, e, o) =>
            {
                h.Add(new EFContextOperationHandler());
                var authorizeAttribute = o.Attributes.OfType<AuthorizationAttribute>().FirstOrDefault();
                if (authorizeAttribute != null)
                {
                    h.Add(new AuthorizationOperationHandler(authorizeAttribute));
                }
                var contentAttribute = o.Attributes.OfType<ContentParamAttribute>().FirstOrDefault();
                if (contentAttribute != null)
                {
                    h.Add(new ContentParameterHandler(contentAttribute));
                }
            };

            // Add error handler
            ErrorHandlers = (handlers, endpoint, descriptions) => handlers.Add(new ApiErrorHandler());

            /* JSON.NET Formatter
             * Inserted at first position to take preference over other JSON formatters
             */
            Formatters.Insert(0, MvcApplication.jsonNetFormatter);
        }
    }
}